package com.dosimple.comparedatabase.util;

import org.apache.commons.dbcp2.BasicDataSource;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @auther: baolw
 * @date: 2018/6/19 0019 下午 4:43
 */
public class DBUtils {
    public static final String SOURCE = "SOURCE";
    public static final String TARGET = "TARGET";
    public static final Map<String, Map<String, BasicDataSource>> dbs = new HashMap<>();
    public static final Map<String, String> aliasDbName = new HashMap<>();

    private static BasicDataSource createDataSource(String url, String user, String password) {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setMaxTotal(10);
        dataSource.setUrl(url);
        dataSource.setUsername(user);
        dataSource.setPassword(password);
        dataSource.setMaxWaitMillis(10000);
        dataSource.setMinIdle(1);
        return dataSource;
    }

    public static String createCompareConnection(String sourceUrl, String sourceUser, String sourcePassword, String targetUrl
            , String targetUser, String targetPassword, String aliasName) {
        BasicDataSource source = createDataSource(sourceUrl, sourceUser, sourcePassword);
        BasicDataSource target = createDataSource(targetUrl, targetUser, targetPassword);
        Map<String, BasicDataSource> compare = new HashMap<>();
        compare.put(SOURCE, source);
        compare.put(TARGET, target);
        String id = UUID.randomUUID().toString().replace("-", "");
        dbs.put(id, compare);
        aliasDbName.put(aliasName, id);
        return id;
    }

    public static boolean deleteDatabase(String baseId) {
        dbs.remove(baseId);
        final String[] key = {null};
        aliasDbName.forEach((k, v)->{
            if (v.equals(baseId)) {
                key[0] = k;
            }
        });
        aliasDbName.remove(key[0]);
        return true;
    }

    public static void closeConn(Connection conn) {
        if (conn == null) {
            return;
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException ("归还连接错误！",e);
        }
    }

    public static void closeStatement(Statement st) {
        if (st == null) {
            return;
        }
        try {
            st.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException ("归还连接错误！",e);
        }
    }

    public static void closeResultSet(ResultSet rs) {
        if (rs == null) {
            return;
        }
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
            throw new RuntimeException ("归还连接错误！",e);
        }
    }
}
